function redirectToVideoUrl(details, source) {
  const gfycatUrlPattern = /^https:\/\/(?:[\w-]+\.)?gfycat\.com(?:\/.*)?$/;

  chrome.storage.local.get({ navStrategy: "onBeforeNavigate" }, (result) => {
    if (source !== result.navStrategy) return;
    if (details.url.match(gfycatUrlPattern) === null) return;

    const destinationUrl = "https://web.archive.org/web/1if_/" + details.url;
    console.log(`[${source}] Redirecting to ${destinationUrl}`);

    chrome.tabs.update(details.tabId, {
      url: destinationUrl,
    });
  });
}

chrome.webNavigation.onBeforeNavigate.addListener((details) =>
  redirectToVideoUrl(details, "onBeforeNavigate")
);

chrome.webNavigation.onErrorOccurred.addListener((details) =>
  redirectToVideoUrl(details, "onErrorOccurred")
);
